package com.xiaoyu.im;

import androidx.annotation.Nullable;
import android.text.TextUtils;

import com.xiaoyu.im.provider.ChatIdMapper;
import in.srain.cube.util.StringUtil;

import org.jetbrains.annotations.NotNull;

public class ChatToken {

    private static final ChatToken EMPTY = new ChatToken("", false);

    private final String mId;
    private final boolean mUidType;
    private volatile String mChatId; // immutable after initialisation
    private volatile String mUid; // immutable after initialisation

    private ChatToken(String id, boolean uidType) {
        if (id == null) {
            throw new IllegalArgumentException();
        }
        this.mId = id;
        this.mUidType = uidType;
    }

    public static ChatToken forUid(String uid) {
        return new ChatToken(uid, true);
    }

    public static ChatToken forChatId(String chatId) {
        return new ChatToken(chatId, false);
    }

    public static ChatToken createOrEmpty(@Nullable String chatId, @Nullable String uid) {
        if (!TextUtils.isEmpty(chatId)) {
            return forChatId(chatId);
        }
        if (!TextUtils.isEmpty(uid)) {
            return forUid(uid);
        }
        return EMPTY;
    }

    public String getUid() {
        if (mUid == null) {
            mUid = mUidType ? mId : ChatIdMapper.getInstance().getUid(mId);
        }
        return StringUtil.blankIfNull(mUid);
    }

    public String getChatId() {
        if (mChatId == null) {
            mChatId = !mUidType ? mId : ChatIdMapper.getInstance().getChatIdByUid(mId);
        }
        return StringUtil.blankIfNull(mChatId);
    }

    public boolean hasUid() {
        return !TextUtils.isEmpty(getUid());
    }

    public boolean hasChatId() {
        return !TextUtils.isEmpty(getChatId());
    }

    public boolean isMatch(ChatToken o) {
        if (this == o) {
            return true;
        }
        if (mUidType && o.mUidType && mId.equals(o.mId)) {
            return true;
        }
        final String chatId = getChatId();
        return chatId != null && chatId.equals(o.getChatId());
    }

    @NotNull
    @Override
    public String toString() {
        return "ChatToken{" +
                "id='" + mId + '\'' +
                ", mUidType=" + mUidType +
                ", getUid=" + getUid() +
                ", getChatId=" + getChatId() +
                '}';
    }
}
